from rest_framework import serializers

from goods.models import SKU


class CartSerializer(serializers.Serializer):

    sku_id = serializers.IntegerField(label='商品id',required=True,min_value=1)
    count = serializers.IntegerField(label='商品数量',required=True,min_value=1)
    selected = serializers.BooleanField(label='商品选中状态',default=True)


    def validate(self, attrs):
        sku_id = attrs.get('sku_id')
        count = attrs.get('count')

        try:
            sku = SKU.objects.get(pk=sku_id)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('该商品不存在')

        if sku.stock < count:
            raise serializers.ValidationError('库存不足')

        return attrs


class CartSKUSerializer(serializers.ModelSerializer):
    count = serializers.IntegerField(label='商品数量')
    selected = serializers.BooleanField(label='商品选中状态')
    class Meta:
        model = SKU
        fields = ['id','name','default_image_url','price','count','selected']